package com.bear.newsset.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bear.newsset.R;
import com.bear.newsset.dao.sql.NewsDataSQL;
import com.bear.newsset.entity.NewsListEntity;
import com.bear.newsset.entity.NewsParamEntity;
import com.bear.newsset.util.ActionUtil;
import com.bear.newsset.util.LogUtils;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 新闻列表View
 * 加载数据时隐藏RecyclerView，加载完毕后显示
 */
public class NewsView extends FrameLayout {
    private Context mContext;
    private ThisHandler mThisHandler;
    private NewsListRecyclerView xrvNewsList;
    private ImageView mLoadView;
    private TextView mFailureView;

    private NewsDataSQL mNewsSQL;

    public NewsView(Context context) {
        super(context);
        init(context);
    }

    public NewsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context mContext) {
        this.mContext = mContext;
        mThisHandler = new ThisHandler( this );
        mNewsSQL = NewsDataSQL.getInstance();
        initView();
        initListener();
        addView( mLoadView );
        addView( xrvNewsList );
        addView( mFailureView );
    }

    private void initView() {
        LayoutParams lpFull = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        //父控件设置布局参数
        setLayoutParams(lpFull);
        //获取新闻列表View
        xrvNewsList = new NewsListRecyclerView(mContext);
        //创建加载等待View
        mLoadView = createLoadView();
        //创建加载失败View
        mFailureView = createFailureView();
        mFailureView.setVisibility( View.GONE );
    }

    private void initListener() {
        //长按弹出更多的选项事件监听器
        xrvNewsList.setOnClickInsideMoreBtnListener((v, type, isSelect, itemData, position) -> {
            String text;
            switch ( type ) {
                case GIVE_LIKE:     //点赞
                    if( !isSelect ) break;
                    Toast.makeText(mContext, "点赞成功！", Toast.LENGTH_SHORT).show();
                    break;
                case COLLECT:       //收藏
                    text = isSelect ? "已收藏" : "取消收藏";
                    Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
                    break;
                case SHARE:         //分享
                    //发起分享
                    ActionUtil.startShare( v.getContext(), itemData.getItemData().getUrl() );
                    break;
            }
        });

        //新闻刷新状态事件监听器
        xrvNewsList.setOnRefreshStatusListener( new NewsListRecyclerView.OnRefreshStatusListener() {
            @Override
            public void onLoading() {
                LogUtils.d("NewsView.onLoading", "正在拉取数据");
            }
            @Override
            public void onResponse(NewsParamEntity paramEntity, List<NewsListEntity> list) {
                LogUtils.d("NewsView.onResponse", "拉取成功！");
                //保存拉取得数据到数据库
                mNewsSQL.insertNewsData(
                        paramEntity.getMainLableId(), paramEntity.getChildLableId(), list
                );
                if( list.size() == 0 ) {
                    mThisHandler.sendEmptyMessage( 666 );
                }
                //隐藏加载失败View
                mThisHandler.sendEmptyMessage( 401 );
            }
            @Override
            public void onFailure() {
                LogUtils.d("NewsView.onFailure", "拉取失败！");
                if( xrvNewsList.getNewsDataListSize() > 0 ) return;
                //显示加载失败View
                mThisHandler.sendEmptyMessage( 201 );
                xrvNewsList.setEnabled( true );
            }
        });

        //加载失败View点击事件监听器
        mFailureView.setOnClickListener(v -> {
            //请求新闻数据，因为之前已经设置过参数了，所以没必要设置参数
            xrvNewsList.requestNewsData();
            //隐藏加载失败View
            mThisHandler.sendEmptyMessage( 401 );
        });
    }

    /**
     * 创建加载等待View
     * @return  {@link ImageView}
     */
    private ImageView createLoadView() {
        ImageView v = new ImageView( mContext );
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        v.setLayoutParams( lp );
        v.setImageResource(R.drawable.ic_bg_news_list_load_img);
        v.setScaleType(ImageView.ScaleType.FIT_XY);
        v.setBackgroundColor(getResources().getColor(R.color.colorWhite));
        return v;
    }

    /**
     * 创建加载失败View
     * @return  {@link TextView}
     */
    private TextView createFailureView() {
        TextView v = new TextView( mContext );
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        v.setLayoutParams( lp );
        v.setText( "TAT~ 新闻不见了！\n点击空白处再试试，万一成功了呢！" );
        v.setTextSize( 14 );
        v.setTextColor( getResources().getColor( R.color.colorChild ) );
        v.setBackgroundResource( R.color.colorWhite );
        v.setGravity( Gravity.CENTER );
        v.setClickable( true );
        return v;
    }

    public NewsListRecyclerView getNewsListView() { return xrvNewsList; }

    public ImageView getLoadView() { return mLoadView; }

    public TextView getFailureView() { return mFailureView; }

    private static class ThisHandler extends Handler {
        private NewsView mView;
        ThisHandler(NewsView view) {
            mView = new WeakReference<>(view).get();
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch ( msg.what ) {
                case 200:   //显示新闻列表
                    mView.xrvNewsList.setVisibility( View.VISIBLE );
                    break;
                case 201:   //显示失败View
                    mView.mFailureView.setVisibility( View.VISIBLE );
                    break;
                case 400:   //隐藏新闻列表
                    mView.xrvNewsList.setVisibility( View.INVISIBLE );
                    break;
                case 401:   //隐藏失败View
                    mView.mFailureView.setVisibility( View.INVISIBLE );
                    break;
                case 666:
                    Toast.makeText(
                            mView.mContext, "惊！！！居然没有新闻了！", Toast.LENGTH_LONG
                    ).show();
                    break;
            }
        }
    }
}
